# _*_ encoding:utf-8 _*_
from django.contrib.auth.hashers import make_password
from django_redis import get_redis_connection

from rest_framework import serializers
from rest_framework.exceptions import ValidationError

from user.models import User


class UserModelSerializer(serializers.ModelSerializer):
    sms_code = serializers.CharField(write_only=True)

    class Meta:
        model = User
        fields = [
            'id',
            'username',
            'mobile',
            'avatar',
            'password',
            'sms_code'
        ]

        extra_kwargs = {
            'password': {'write_only': True, 'min_length': 6, 'max_length': 16},
            'sms_code': {'write_only': True},
            'username': {'min_length': 3, 'max_length': 20},
        }

    def validate(self, attrs):
        sms_code = attrs.pop('sms_code')

        conn = get_redis_connection('verify_code')
        sms_code_server = conn.get(f"sms_{attrs['mobile']}")

        if not sms_code_server:
            raise ValidationError('无效验证码')

        if sms_code != sms_code_server.decode():
            raise ValidationError('无效验证码')

        raw_password = attrs.get('password')
        attrs['password'] = make_password(raw_password)

        return attrs

















